//
//  SingerList.m
//  YanMusicPlayer
//
//  Created by 1564335 on 15-6-11.
//  Copyright (c) 2015年 胡岩 All rights reserved.
//

#import "SingerList.h"
#import "SingerListCollectionViewCell.h"
#import "SingerListModel.h"
#import "SingerListHeaderView.h"
#import "SingerListCollectionView.h"

@interface SingerList ()<UICollectionViewDataSource, UICollectionViewDelegate, TouchTableViewDelegate>
{
    CGFloat x;
}
@property(nonatomic, strong) SingerListCollectionView *SingerListCollection;

@property(nonatomic, strong) NSString *url;

@property(nonatomic, strong) NSMutableArray *arrayData;

@property(nonatomic, strong) SingerListHeaderView *headerView;

@property(nonatomic, assign) CGPoint startPoint;

@property(nonatomic, strong) UIActivityIndicatorView *activity;

@end

@implementation SingerList

- (instancetype)initWithFrame:(CGRect)frame :(NSString *)url
{
    _url = [NSString string];
    _url = url;
    _arrayData = [NSMutableArray array];
    self = [super initWithFrame:frame];
    if (self) {
        _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        [self addSubview:_activity];
        [_activity startAnimating];
        _activity.center = self.center;
        [self netWorkMananger];
    }
    return self;
}

- (void)tableView:(UICollectionView *)tableView touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.sendDelegate sendTouchEnd];
    self.SingerListCollection.scrollEnabled = YES;
    self.SingerListCollection.allowsSelection = YES;
}

- (void)tableView:(UICollectionView *)tableView touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    self.startPoint = [touch locationInView:self];
}

- (void)tableView:(UICollectionView *)tableView touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint newPoint = [touch locationInView:self];
    x = newPoint.x - self.startPoint.x;
    if (x > 5 || x < -5) {
        self.SingerListCollection.scrollEnabled = NO;
        self.SingerListCollection.allowsSelection = NO;
        [self.sendDelegate getTouch:x];
    }
}

- (void)netWorkMananger
{
    NSString *path = [[URLPath SingerListURL] stringByAppendingFormat:@"%@&page=1&size=1000", _url];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = dic[@"data"];
        for (NSDictionary *dic in array) {
            SingerListModel *model = [[SingerListModel alloc] initWithDic:dic];
            [self.arrayData addObject:model];
        }
        [self createView];
        [_activity stopAnimating];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [_activity stopAnimating];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }];
}



- (void)createView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 5;
    layout.minimumLineSpacing = 5;
    layout.headerReferenceSize = CGSizeMake(self.frame.size.width, (self.frame.size.width - 25) / 2 + 15);
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    layout.itemSize = CGSizeMake((self.frame.size.width - 30) / 4, (self.frame.size.width - 30) / 6);
    self.SingerListCollection = [[SingerListCollectionView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) collectionViewLayout:layout];
    self.SingerListCollection.backgroundColor = [UIColor whiteColor];
    self.SingerListCollection.delegate = self;
    self.SingerListCollection.dataSource = self;
    self.SingerListCollection.touchDelegate = self;
    _SingerListCollection.showsVerticalScrollIndicator = NO;
    _SingerListCollection.backgroundColor = [UIColor clearColor];
    [self addSubview:self.SingerListCollection];
    [self.SingerListCollection  registerClass:[SingerListHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    
    [self.SingerListCollection registerClass:[SingerListCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
   
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    SingerListModel *model = [self.arrayData objectAtIndex:indexPath.row];
//    MusicModel *musicModel = [MusicModel getMusicModel];
//    musicModel.pic_url = model.pic_url;
//    [[MusicPlayer shareInstance].list addObject:musicModel];
    [self.sendDelegate goBack:model.singer_name];
}

- (void)imageTap:(UITapGestureRecognizer *)tap
{
    UIView *view = (UIView *)tap.view;
    SingerListModel *model = [self.arrayData objectAtIndex:view.tag];
//    MusicModel *musicModel = [MusicModel getMusicModel];
//    musicModel.pic_url = model.pic_url;
//    [[MusicPlayer shareInstance].list addObject:musicModel];
    [self.sendDelegate goBack:model.singer_name];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
//    UICollectionReusableView *reusableView = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        self.headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView" forIndexPath:indexPath];
        // SingerHeaderView
        int num = 0;
        for (int i = 0; i < 8; i++) {
            CGFloat childHeight = 0;
            CGFloat childWidth = 0;
            if (i  > 3) {
                childHeight = (self.frame.size.width - 25) / 4 + 5;
                num = i - 4;
            } else {
                num = i;
            }
            if (i == 0) {
                childWidth = 5;
            } else {
                childWidth = 5 + (5 + (self.frame.size.width - 25) / 4) * num;
            }
            SingerListModel *model = [self.arrayData objectAtIndex:i];
            UIImageView *childView = [[UIImageView alloc] initWithFrame:CGRectMake(childWidth, 5 + childHeight, (self.frame.size.width - 25) / 4, (self.frame.size.width - 25) / 4)];
            [childView setImageWithURL:[NSURL URLWithString:model.pic_url] placeholderImage:nil];
            childView.userInteractionEnabled = YES;
            childView.layer.cornerRadius = 5;
            childView.layer.masksToBounds = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTap:)];
            childView.tag = i;
            [childView addGestureRecognizer:tap];
            
            UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, childView.frame.size.height - 20, childView.frame.size.width, 20)];
            nameLabel.text = model.singer_name;
            nameLabel.font = [UIFont systemFontOfSize:15];
            nameLabel.backgroundColor = [UIColor blackColor];
            nameLabel.alpha = 0.7;
//            nameLabel.layer.cornerRadius = 4;
//            nameLabel.layer.masksToBounds = YES;
            nameLabel.textColor = [UIColor whiteColor];
            [childView addSubview:nameLabel];
            [self.headerView addSubview:childView];
        }
    }
    return self.headerView;
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SingerListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    SingerListModel *model = [self.arrayData objectAtIndex:indexPath.row];
    [cell setSingerListModel:model];
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arrayData.count;
}













@end
